class Registration < ActiveRecord::Base
  belongs_to :student
  belongs_to :timeslot

  validates :register_time, :presence => true
  validates :student, :presence => true
  validates :timeslot, :presence => true

  validate :timeslot_has_max_one_registration, :on => :create
  validate :student_has_max_one_registration, :on => :create
  validate :timeslot_cannot_be_registered_too_late, :on => :create
  validate :registration_cannot_be_cancelled_too_late, :on => :update

  def timeslot_has_max_one_registration
    if timeslot.registered?
      errors.add(:timeslot, "can't have more than one registration")
    end
  end

  def student_has_max_one_registration
    if student.has_active_registration?
      errors.add(:student, "can't have more than one registration")
    end
  end

  def timeslot_cannot_be_registered_too_late
    if timeslot.start_time < Time.now.advance(:hours => 2)
      errors.add(:timeslot, "can't be registered closer than 2 hours from beginning")
    end
  end

  def registration_cannot_be_cancelled_too_late
    if timeslot.start_time < cancel_time.advance(:days => 1)
      errors.add(:cancel_time, "can't be closer than 24 hours to timeslot start")
    end
  end

  def cancel!
    self.cancel_time = Time.now
    self.save(:validate => false)
  end

  def driving_lesson
    timeslot.driving_lesson
  end

  def cancellation_report
    timeslot.cancellation_report
  end
end
